//
//  ShellSelectCountryViewController.m
//  VVBTC
//
//  Created by lvzhao on 2019/7/15.
//  Copyright © 2019 链动科技. All rights reserved.
//

#import "ShellSelectCountryViewController.h"
#import "LZBaseTableView.h"

@interface ShellSelectCountryViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSMutableArray *rowArr;
@property (nonatomic,strong) NSMutableArray *sectionArr;

//滑动的View
@property (nonatomic,strong) LZBaseTableView *tableView;
@end

@implementation ShellSelectCountryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = LZLocalizedString(@"选择国家");
    
    [self setupUI];
}


#pragma mark - setupUI
- (void)setupUI{
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    self.tableView.tableHeaderView = [UIView new];
                                    
    //获取手机区号
    [self getFindAreaCode];
}


#pragma mark - UITableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //section
    return self.rowArr.count;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //row
    return [self.rowArr[section] count];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //viewforHeader
    id label = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    if (!label) {
        label = [[UILabel alloc] init];
        [label setFont:k_textBoldFont(18)];
        [label setTextColor:UIColorHex(0xFFFFFF)];
        [label setBackgroundColor:UIColorHex(0x04172A)];
    }
    [label setText:[NSString stringWithFormat:@"   %@",self.sectionArr[section]]];
    return label;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return index;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return _sectionArr;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShellSelectCountryCell *countryCell = [tableView dequeueReusableCellWithIdentifier:@"ShellSelectCountryCell"];
    ShellCountryModel *countryModel = self.rowArr[indexPath.section][indexPath.row];
    countryCell.countryModel = countryModel;
    return countryCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ShellCountryModel *countryModel = self.rowArr[indexPath.section][indexPath.row];
    if(self.selectSubject){
        [self.selectSubject sendNext:countryModel];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - actions

#pragma mark - custool
- (NSMutableArray *)sortCountryModel:(NSMutableArray *)countryModels{
    
    NSMutableArray *ans = [[NSMutableArray alloc] init];
    
    NSArray *serializeArray = [(NSArray *)countryModels sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {//排序
        int i;
        NSString *strA = ((ShellCountryModel *)obj1).pinyin;
        NSString *strB = ((ShellCountryModel *)obj2).pinyin;
        for (i = 0; i < strA.length && i < strB.length; i ++) {
            char a = [strA characterAtIndex:i];
            char b = [strB characterAtIndex:i];
            if (a > b) {
                return (NSComparisonResult)NSOrderedDescending;//上升
            }
            else if (a < b) {
                return (NSComparisonResult)NSOrderedAscending;//下降
            }
        }
        
        if (strA.length > strB.length) {
            return (NSComparisonResult)NSOrderedDescending;
        }else if (strA.length < strB.length){
            return (NSComparisonResult)NSOrderedAscending;
        }else{
            return (NSComparisonResult)NSOrderedSame;
        }
    }];
        
    char lastC = '1';
    NSMutableArray *data;
    NSMutableArray *oth = [[NSMutableArray alloc] init];
    for (ShellCountryModel *countryModel in serializeArray) {
        char c = [countryModel.pinyin characterAtIndex:0];
        if (!isalpha(c)) {
            [oth addObject:countryModel];
        }
        else if (c != lastC){
            lastC = c;
            if (data && data.count > 0) {
                [ans addObject:data];
            }
            
            data = [[NSMutableArray alloc] init];
            [data addObject:countryModel];
        }
        else {
            [data addObject:countryModel];
        }
    }
    if (data && data.count > 0) {
        [ans addObject:data];
    }
    if (oth.count > 0) {
        [ans addObject:oth];
    }
    return ans;
}
    

- (NSMutableArray *)getCountryListSectionBy:(NSMutableArray *)array{
    NSMutableArray *section = [[NSMutableArray alloc] init];
    
    //添加搜索的图片
//    [section addObject:UITableViewIndexSearch];
    for (NSArray *item in array) {
        ShellCountryModel *countryModel = [item objectAtIndex:0];
        char c = [countryModel.pinyin characterAtIndex:0];
        
        //添加最后已数组, 开头, 或者其他开头的#
        if (!isalpha(c)) {
            c = '#';
        }
        [section addObject:[NSString stringWithFormat:@"%c", toupper(c)]];
    }
    return section;
}

    
    
    

///!!!:获取手机区号 国家
- (void)getFindAreaCode{

    NSString *fieldName = [[NSBundle mainBundle] pathForResource:@"Country" ofType:@"plist"];
    NSArray *dataArray = [NSArray arrayWithContentsOfFile:fieldName];
    NSMutableArray *countryModels = [[NSMutableArray alloc] init];
    for(int i = 0; i < dataArray.count; i++){
        ShellCountryModel *countryModel = [ShellCountryModel new];
        countryModel.name = dataArray[i];
        [countryModels addObject:countryModel];
    }
    
    //去排序
    self.rowArr = [self sortCountryModel:countryModels];
    self.sectionArr = [self getCountryListSectionBy:self.rowArr];
    
    [self.tableView reloadData];

    
    NSLog(@"self.rowArr === %@",self.rowArr);
    NSLog(@"sectionArr === %@",self.sectionArr);
}
#pragma mark - get && set
- (LZBaseTableView *)tableView{
    if(!_tableView){
        _tableView = [[LZBaseTableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = COLOR_BACKGROUND;
        _tableView.rowHeight = 50;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [_tableView setSectionIndexBackgroundColor:[UIColor clearColor]];
        [_tableView setSectionIndexColor:UIColorHex(0x4AB2E7)];
        [_tableView registerClass:[ShellSelectCountryCell class] forCellReuseIdentifier:@"ShellSelectCountryCell"];
    }
    return _tableView;
}

@end

@implementation ShellCountryModel

- (void)setName:(NSString *)name{
    _name = name;
    _pinyin = [NSString pinyinChinese:name];
}
@end


@interface ShellSelectCountryCell ()

@property (nonatomic,strong) UILabel *countryLabel;
@property (nonatomic,strong) UILabel *codeLabel;

@end

@implementation ShellSelectCountryCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){

        self.backgroundColor = UIColorHex(0x031D32);

        [self setupView];
    }
    return self;
}

#pragma mark - setupView
- (void)setupView{
    [self.contentView addSubview:self.countryLabel];
    [self.countryLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_equalTo(self.contentView.mas_centerY);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(23);
        
    }];
    
    [self.contentView addSubview:self.codeLabel];
    [self.codeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-37);
        make.centerY.mas_equalTo(self.contentView.mas_centerY);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(23);
        
    }];
}
#pragma mark - actions
- (void)setCountryModel:(ShellCountryModel *)countryModel{

    if (countryModel.isCountry) {
        self.codeLabel.hidden = YES;
    }
    self.countryLabel.text = countryModel.name;
    self.codeLabel.text = countryModel.value;
}
#pragma mark - custool

#pragma mark - get && set
- (UILabel *)countryLabel{
    if(!_countryLabel){
        _countryLabel = [UILabel lz_labelWithText:@"" fontSize:k_textFontName(@"Roboto-Medium", 16) color:UIColorHex(0x6699BF)];
    }
    return _countryLabel;
}

- (UILabel *)codeLabel{
    if(!_codeLabel){
        _codeLabel = [UILabel lz_labelWithText:@"" fontSize:k_textFontName(@"Roboto-Regular", 15) color:UIColorHex(0x8F95AA)];
        _codeLabel.textAlignment = NSTextAlignmentRight;
    }
    return _codeLabel;
}

@end
